<template>
	<view class="container">
		<u-sticky>
			<view class="header" :style="{ paddingTop: menuButtonInfo.top + 'px' }">
				<view class="title" :style="{ height: menuButtonInfo.height + 'px', lineHeight: menuButtonInfo.height + 'px' }">代理商</view>
				<view class="content">
					<view class="userinfo">
						<view class="head">
							<image :src="states.userInfo.header"></image>
						</view>
						<view class="info">
							<view class="name">
								<text class="first">{{ states.userInfo?.nickname }}</text>
								<text class="tag">{{ states.userInfo?.level_text }}</text>
								<uni-icons type="help" size="16" color="#fff" @click="help"></uni-icons>
							</view>
							<view class="subname">代理商编号：{{ states.userInfo?.number }}</view>
						</view>
					</view>
					<view class="msgTips" @click="gotoMsgPage">
						<uni-badge :text="num" type="success" size="small" absolute="rightTop" :offset="[3, 3]">
							<uni-icons type="chat" size="24" color="#fff"></uni-icons>
						</uni-badge>
					</view>
				</view>
			</view>
			<view class="main">
				<view class="block-item flex-center">
					<view class="block">
						<view class="money">￥{{ states.userInfo.money_tixian }}</view>
						<view class="msg" @click="gotoPage(1)">
							<text>可提现金额</text>
							<uni-icons type="right" size="16" color="#999"></uni-icons>
						</view>
					</view>
					<view class="verticalLine"></view>
					<view class="block">
						<view class="money">￥{{ states.userInfo.money_dong }}</view>
						<view class="msg" @click="gotoPage(2)">
							<text>冻结金额</text>
							<uni-icons type="right" size="16" color="#999"></uni-icons>
						</view>
					</view>
				</view>
			</view>
		</u-sticky>
		<view class="warp">
			<view class="block-item">
				<view class="pink">
					<view class="center">
						<view class="money">{{ states.userInfo.money_tui }}</view>
						<view class="subtitle" @click="gotoPage(3)">
							<text>推广收益</text>
							<uni-icons type="right" size="14" color="#999"></uni-icons>
						</view>
					</view>
					<view class="center">
						<view class="money">{{ states.userInfo.money_gao_total }}</view>
						<view class="subtitle" @click="gotoPage(4)">
							<text>广告收益</text>
							<uni-icons type="right" size="14" color="#999"></uni-icons>
						</view>
					</view>
					<view class="center">
						<view class="money">{{ states.userInfo.money_ji_total }}</view>
						<view class="subtitle" @click="gotoPage(5)">
							<text>激活奖励</text>
							<uni-icons type="right" size="14" color="#999"></uni-icons>
						</view>
					</view>
				</view>
				<view class="flexjus">
					<view class="content">本月激活数量：{{ states.userInfo?.jihuo_count }}台</view>
					<view class="flex">
						<block v-if="states.userInfo?.jihuo_count > states.userInfo?.jihuo_msg?.list[1]?.num">
							<view class="red">{{ states.userInfo?.jihuo_msg?.list[1]?.num }}台¥{{ states.userInfo?.jihuo_msg?.list[1]?.money }}</view>
						</block>
						<view class="red" v-else>{{ states.userInfo?.jihuo_msg?.list[0]?.num }}台¥{{ states.userInfo?.jihuo_msg?.list[0]?.money }}</view>
						<view class="red">{{ states.userInfo?.jihuo_msg?.list[2]?.num }}台/¥{{ states.userInfo?.jihuo_msg?.list[2]?.money }}</view>
					</view>
				</view>
				<view class="progressBar">
					<u-line-progress active-color="#FF5668" :percentage="total" :showText="false" height="15"></u-line-progress>
				</view>
				<block v-for="(item, index) in states.userInfo?.jihuo_msg?.msg.split('\n')" :key="index">
					<view class="text">{{ item }}</view>
				</block>
			</view>
			<view class="block-item flex-center">
				<view class="item">
					本月完成
					<view class="numbox">
						<text style="opacity: 0; height: 42rpx; line-height: 42rpx">{{ states.userInfo?.jihuo_count }}</text>
						<view class="numwarp" :style="{ transform: `translateY(-${currentPosition}rpx)` }">
							<view class="red" v-for="(item, index) in states.numbers" :key="index">{{ item }}</view>
						</view>
					</view>
					个
				</view>
				<view class="item">
					距离下一目标
					<view class="numbox">
						<text style="opacity: 0; height: 42rpx; line-height: 42rpx">{{ states.userInfo?.mubiao_count }}</text>
						<view class="numwarp" :style="{ transform: `translateY(-${currentPosition2}rpx)` }">
							<view class="red" v-for="(item, index) in states.numbers2" :key="index">{{ item }}</view>
						</view>
					</view>
					个
				</view>
			</view>
			<view class="block-item">
				<view class="tab">
					<view :class="['tab-item', { current: current == 1 }]" @click="toggle(1)">广告收入</view>
					<view :class="['tab-item', { current: current == 2 }]" @click="toggle(2)">推广收入</view>
				</view>
				<scroll-view scroll-x="true" class="noScrollBar" v-show="current == 2">
					<view class="tabs">
						<view :class="['tabs-item', { current: select == 1 }]" @click="toggle2(1)">全部</view>
						<view :class="['tabs-item', { current: select == 2 }]" @click="toggle2(2)">今日</view>
						<view :class="['tabs-item', { current: select == 3 }]" @click="toggle2(3)">昨日</view>
						<view :class="['tabs-item', { current: select == 4 }]" @click="toggle2(4)">本周</view>
						<view :class="['tabs-item', { current: select == 5 }]" @click="toggle2(5)">上周</view>
						<view :class="['tabs-item', { current: select == 6 }]" @click="toggle2(6)">本月</view>
						<view :class="['tabs-item', { current: select == 7 }]" @click="toggle2(7)">
							<text>自定义</text>
							<uni-datetime-picker class="date" :start="startDate" :end="endDate" :value="currentDate" @change="selectDate" type="daterange">
								<view style="opacity: 0; height: 54rpx">自定义</view>
							</uni-datetime-picker>
						</view>
					</view>
				</scroll-view>
				<view class="timeRange" v-show="select == 7">{{ currentDate[0] }} 至 {{ currentDate[1] }}</view>
				<view class="flex statistics" v-show="current == 2">
					<view class="label">总金额：</view>
					<view class="red">{{ state.total_price }}</view>
					<view class="label">激活VIP：</view>
					<view class="red">{{ state.vip_user_count }}</view>
				</view>
				<view class="table" v-show="current == 1">
					<view class="thead">
						<view class="th">设备ID</view>
						<view class="th">广告条数</view>
						<view class="th">广告总价值</view>
					</view>
					<view class="tbody" v-if="state.list.length">
						<view class="tr" v-for="(item, index) in state.list" :key="index">
							<view class="td one">{{ item.imei }}</view>
							<view class="td tow">{{ item.total }}</view>
							<view class="td three">￥{{ item.price }}</view>
						</view>
					</view>
					<view class="empty" v-else style="height: 20vh">
						<u-empty text="暂无数据" mode="list"></u-empty>
					</view>
				</view>
				<view class="charts-box" ref="charts" v-show="current == 2">
					<l-echart ref="chartRef"></l-echart>
					<!-- <qiun-data-charts class="charts-box" type="line" :reshow="show" :opts="chartData.opts" :chartData="chartData"></qiun-data-charts> -->
					<view class="empty">
						<u-empty text="暂无数据"></u-empty>
					</view>
				</view>
			</view>
			<view class="block-item noBackgroundColor">
				<view class="tab">
					<view :class="['tab-item', { current: active == 3 }]" @click="toggle3(3)">推广订单</view>
					<view :class="['tab-item', { current: active == 4 }]" @click="toggle3(4)">推广用户</view>
				</view>
				<view class="list" v-show="active == 3">
					<block v-if="state.list3.length">
						<view class="list-item flex" v-for="(item, index) in state.list3" :key="index">
							<view class="img">
								<image :src="item.goods_thumb"></image>
							</view>
							<view class="info">
								<view class="name">{{ item.goods_title }}</view>
								<view class="time">{{ item.created_at }}</view>
							</view>
						</view>
					</block>
					<view class="empty" v-else style="height: 20vh">
						<u-empty text="暂无数据" mode="list"></u-empty>
					</view>
				</view>
				<view class="list" v-show="active == 4">
					<block v-if="state.list4.length">
						<view class="list-item flexjus" v-for="(item, index) in state.list4" :key="index">
							<view class="left">
								<view class="head">
									<image :src="item.avatar_url"></image>
								</view>
								<view class="info">
									<view class="top">
										<text class="name">{{ item.nickname }}</text>
										<text class="tag" v-if="item.bao">七天退款保障中</text>
									</view>
									<view class="mobile">{{ item.tel }}</view>
								</view>
							</view>
							<view class="right">
								<view class="money">+￥{{ item.reward }}</view>
								<view class="time">{{ item.created_at }}</view>
							</view>
						</view>
					</block>
					<view class="empty" v-else style="height: 20vh">
						<u-empty text="暂无数据" mode="list"></u-empty>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { reactive, ref, nextTick, computed } from 'vue';
// import qiunDataCharts from '@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue';
const echarts = require('../../uni_modules/lime-echart/static/echarts.min');
import { dayjs } from '@/static/dayjs.min.js';
import { get } from '@/request/index.js';
import { onLoad, onShow } from '@dcloudio/uni-app';

const charts = ref();
const states = reactive({
	userInfo: {
		header: '../../static/images/defaultHead.png'
	},
	numbers: [],
	numbers2: []
});

// 获取屏幕边界到安全区域距离
const menuButtonInfo = uni.getMenuButtonBoundingClientRect();

onLoad(async () => {
	await getUserInfo();
	await getMessageData();
	await getServerData(1);
	await getServerData(3);
});

onShow(() => {
	setTimeout(() => {
		startScrollAnimation(states?.userInfo?.jihuo_count);
		startScrollAnimation2(states?.userInfo?.mubiao_count);
	}, 1000);
});

//获取用户信息
const getUserInfo = async () => {
	const res = await get('agent/user/info');
	const { code, data } = res;
	if (code == 200) {
		states.numbers = generateNumberList(data.jihuo_count, []);
		states.numbers2 = generateNumberList(data.mubiao_count, []);
		let userinfo = JSON.parse(uni.getStorageSync('userinfo'));
		const newData = levelTransformText(data);
		const datas = { ...states.userInfo, ...userinfo, ...newData };
		states.userInfo = datas;
		uni.setStorageSync('userinfo', JSON.stringify(datas));
	}
};
//代理商等级数字转文字
const levelTransformText = (data) => {
	if (data.level == 1) {
		data.level_text = '一星代理商';
	} else if (data.level == 2) {
		data.level_text = '二星代理商';
	} else if (data.level == 3) {
		data.level_text = '三星代理商';
	} else if (data.level == 4) {
		data.level_text = '四星代理商';
	} else if (data.level == 5) {
		data.level_text = '五星代理商';
	}
	return data;
};

const total = computed(() => {
	const { jihuo_count, mubiao_count } = states.userInfo;
	const num = Math.round((jihuo_count / mubiao_count) * 100);
	return num;
});

//获取未读消息数量
let num = ref(0);
const getMessageData = async () => {
	const res = await get('agent/notice/count');
	if (res.code == 200) {
		num.value = res.data.count;
	}
};

//跳转代理介绍页面
const help = () => {
	uni.navigateTo({
		url: '/pages/dailijieshao/dailijieshao'
	});
};

//跳转消息列表页面
const gotoMsgPage = () => {
	uni.navigateTo({
		url: '/pages/message/message'
	});
};

//本月已完成数量和目标数量，动画滚动效果
const currentPosition = ref(0); // 当前滚动位置
const currentPosition2 = ref(0); // 当前滚动位置
const generateNumberList = (targetNumber, arr) => {
	const start = targetNumber - 9; // 目标数字前10个数字
	const end = targetNumber + 9; // 目标数字后10个数字
	for (let i = start; i <= end; i++) {
		arr.push(Math.abs(i));
	}
	return arr;
};

const startScrollAnimation = (targetNumber) => {
	let startPosition = 0; // 初始滚动位置
	let endPosition = (targetNumber + 9) * 42; // 目标滚动位置
	let startTime = null;
	let animationInterval = setInterval(() => {
		if (!startTime) startTime = Date.now();
		const elapsedTime = Date.now() - startTime;
		const progress = elapsedTime / 1000;
		// 使用easeInOutQuad缓动函数，使滚动效果更平滑
		const easeInOutQuad = (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);
		const scrollPosition = startPosition + (endPosition - startPosition) * easeInOutQuad(progress);
		if (progress >= 1) {
			clearInterval(animationInterval);
			currentPosition.value = endPosition;
		} else {
			currentPosition.value = Math.round(scrollPosition);
		}
	}, 16); // 大约60帧每秒
};
const startScrollAnimation2 = (targetNumber) => {
	let startPosition = 0; // 初始滚动位置
	let endPosition = (targetNumber - (targetNumber - 9)) * 42; // 目标滚动位置
	let startTime = null;
	let animationInterval = setInterval(() => {
		if (!startTime) startTime = Date.now();
		const elapsedTime = Date.now() - startTime;
		const progress = elapsedTime / 1000;
		// 使用easeInOutQuad缓动函数，使滚动效果更平滑
		const easeInOutQuad = (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);
		const scrollPosition = startPosition + (endPosition - startPosition) * easeInOutQuad(progress);
		if (progress >= 1) {
			clearInterval(animationInterval);
			currentPosition2.value = endPosition;
		} else {
			currentPosition2.value = Math.round(scrollPosition);
		}
	}, 16); // 大约60帧每秒
};

// 广告收入和推广收入切换
let current = ref(1);
const toggle = (n) => {
	current.value = n;
	if (n == 2) {
		show.value = true;
	}
	getServerData(n);
};

//周期切换
let select = ref(1);
const toggle2 = (n) => {
	select.value = n;
	getServerData(2);
};

//自定义日期
let startDate = ref('2025-01-01');
let endDate = ref(dayjs().format('YYYY-MM-DD'));
let currentDate = ref([dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]);
const selectDate = (e) => {
	currentDate.value = e;
};

//推广订单和推广用户切换
let active = ref(3);
const toggle3 = (n) => {
	active.value = n;
	getServerData(n);
};

//推广收入图表
let show = ref(false);
let chartData = reactive({
	opts: {},
	categories: [],
	series: []
});
//1广告收入 2推广收入 3推广订单 4推广用户
// list 广告收入数据，chartData 推广收入数据，list3 推广订单数据，list4 推广用户数据
const state = reactive({
	list: [],
	list3: [],
	list4: [],
	total_price: 0,
	vip_user_count: 0
});

const getServerData = async (n) => {
	let params = { type: n };
	if (n == 2) {
		if (select.value == 7) {
			params = {
				type: n,
				tab: select.value,
				time: `${dayjs(currentDate[0]).format('YYYYMMDD')}-${dayjs(currentDate[1]).format('YYYYMMDD')}`
			};
		} else {
			params = {
				type: n,
				tab: select.value
			};
		}
	}
	const res = await get('agent/center/list', params);
	const { data } = res;
	if (n == 1) {
		state.list = data.data;
	} else if (n == 2) {
		state.total_price = data.total_price;
		state.vip_user_count = data.vip_user_count;
		setChartsOptionData(data.list);
	} else if (n == 3) {
		state.list3 = data.data;
	} else if (n == 4) {
		state.list4 = data.data;
	}
};

const chartRef = ref(null);
const option = {
	grid: {
		top: 20,
		right: 0,
		bottom: 20
	},
	xAxis: {
		type: 'category',
		data: []
	},
	yAxis: {
		type: 'value'
	},
	series: [
		{
			data: [],
			type: 'line',
			smooth: true,
			symbol: 'none',
			areaStyle: {
				color: {
					type: 'linear',
					x: 0,
					y: 0,
					x2: 0,
					y2: 1,
					colorStops: [
						{
							offset: 0,
							color: 'rgba(254, 72, 110, .8)' // 起始颜色及透明度（上方）
						},
						{
							offset: 1,
							color: 'rgba(254, 72, 110, 0)' // 结束颜色及透明度（下方，与背景融合）
						}
					],
					globalCoord: false // 使用局部坐标系
				}
			},
			lineStyle: {
				// 使用线性渐变
				color: '#ff5688',
				width: 2 // 线条宽度
			}
		}
	]
};
const setChartsOptionData = async (data) => {
	option.xAxis.data = data.categories;
	option.series[0].data = data.series[0].data;
	// 组件能被调用必须是组件的节点已经被渲染到页面上
	setTimeout(async () => {
		if (!chartRef.value) return;
		const myChart = await chartRef.value.init(echarts);
		myChart.setOption(option);
	}, 300);
};

const setChartsData = async () => {
	chartData.opts = {
		width: 300,
		height: 220,
		color: ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'],
		padding: [15, 10, 0, 15],
		dataLabel: false,
		dataPointShape: false,
		enableScroll: false,
		legend: {},
		xAxis: {
			disableGrid: true
		},
		yAxis: {
			gridType: 'dash',
			dashLength: 2,
			data: [
				{
					min: 0,
					max: 150
				}
			]
		},
		extra: {
			line: {
				type: 'curve',
				width: 2,
				activeType: 'hollow',
				linearType: 'custom',
				onShadow: true,
				animation: 'horizontal'
			}
		}
	};
	//模拟从服务器获取数据时的延时
	setTimeout(() => {
		//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
		let res = {
			categories: ['2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025'],
			series: [
				{
					name: '总金额',
					setShadow: [3, 8, 10, '#1890FF'],
					data: [15, 45, 15, 45, 15, 45, 55, 65]
				}
			]
		};
		chartData.categories = JSON.parse(JSON.stringify(res.categories));
		chartData.series = JSON.parse(JSON.stringify(res.series));

		// console.log(333, chartData);
	}, 500);
};
const gotoPage = (n) => {
	let path = '';
	if (n == 1) {
		path = '/pages/tixian/tixian';
	} else if (n == 2) {
		path = '/pages/dongjiejine/dongjiejine';
	} else if (n == 3) {
		path = '/pages/tuiguangshouyi/tuiguangshouyi';
	} else if (n == 4) {
		path = '/pages/guanggaoshouyi/guanggaoshouyi';
	} else if (n == 5) {
		path = '/pages/jihuoshouyi/jihuoshouyi';
	}
	uni.navigateTo({
		url: path
	});
};
</script>

<style scoped lang="scss">
.charts-box {
	width: 100%;
	height: 440rpx;
}
.tabs-item {
	position: relative;
	z-index: 1;
	.date {
		position: absolute;
		left: 0;
		top: 0;
		padding-right: 0;
		height: 100%;
		z-index: 2;
		&::after {
			display: none;
		}
	}
}
::v-deep .uni-datetime-picker--btn,
::v-deep .uni-calendar-item__weeks-box .uni-calendar-item--checked {
	background-color: #ff5668;
}
::v-deep .uni-calendar-item--multiple {
	.uni-calendar-item--before-checked,
	.uni-calendar-item--after-checked {
		background-color: #ff5668;
	}
}
</style>